//
//  ApiEncryption.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/9/2.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import Moya

class ApiEncryption {

    let publicKey = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpQIp8kJ+1fQbxO8BJW0xvAAjtbFK4MAAR46Q3rvNPKXYVxCJV1MYkJhDGXSenvb2h5Uqr3NsnE1zBH4Q9YWC7EuCySFpTJqvUR89+FUvhM5fr9Vy1hQXlFKunvem/OM2fVjEm4UV7g+tXye6xzomFBNbDh+VkMJoEKDcTFgSlkwIDAQAB\n-----END PUBLIC KEY-----"
    
    static let shared = ApiEncryption()
    
    let aesKey = String.random(16)
    
    func rsa() -> String {
        let encrypted = RSA.encryptString(aesKey, publicKey: publicKey)
        return encrypted ?? ""
    }
    
    func encryptionRequestData(_ data: Data) -> Data {
        guard let dataString = String.init(data: data, encoding: .utf8),
            let encryptedData = AESCrypt.aes128Encrypt(dataString, key: aesKey),
            let jsonData = try? JSONSerialization.data(withJSONObject: ["requestData": encryptedData], options: .prettyPrinted) else {
               return data
        }
        return jsonData
    }
    
}

extension Response {
    
    func decode() -> Response {
        guard let dataString = self.jsonDictionary["data"] as? String,
            let decodeString = AESCrypt.aes128Decrypt(dataString, key: ApiEncryption.shared.aesKey),
            let data = decodeString.data(using: .utf8) else {
                return self
        }
        return Response.init(statusCode: self.statusCode, data: data, request: self.request, response: self.response)
    }
    
}

extension Result where Success == Moya.Response, Failure == MoyaError {
    
    func decode() -> Result<Moya.Response, MoyaError> {
        guard case let .success(response) = self else {
                return self
        }
        return Result.success(response.decode())
    }
    
}
